import javax.sound.sampled.*;
import java.io.*;
import java.net.*;

public class TCPClient {
    private static final String SERVER_IP = "47.76.72.147";
    private static final int TCP_PORT = 4000;
    private static final int UDP_PORT = 5001;

    public static void main(String[] args) {
        // TCP连接阶段，发送UDP端口号
        try (Socket socket = new Socket(SERVER_IP, TCP_PORT);
             PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
             BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()))) {

            out.println(UDP_PORT);
            String response = in.readLine();
            System.out.println("Server says: " + response);

            startUDPSession(); // 开始UDP通话

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void startUDPSession() {
        Thread sendThread = new Thread(TCPClient::sendAudio);
        Thread receiveThread = new Thread(TCPClient::receiveAudio);

        sendThread.start();
        receiveThread.start();
    }

    private static void sendAudio() {
        try (DatagramSocket socket = new DatagramSocket();
             TargetDataLine microphone = AudioUtil.getTargetDataLine()) {
            microphone.start();
            byte[] buffer = new byte[1024];

            while (true) {
                int bytesRead = microphone.read(buffer, 0, buffer.length);
                if (bytesRead > 0) {
                    DatagramPacket packet = new DatagramPacket(buffer, bytesRead, InetAddress.getByName(SERVER_IP), UDP_PORT);
                    socket.send(packet);
                    System.out.println("successfully sent packet!");
                }
            }
        } catch (IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }

    private static void receiveAudio() {
        try (DatagramSocket socket = new DatagramSocket(UDP_PORT);
             SourceDataLine speakers = AudioUtil.getSourceDataLine()) {
            speakers.start();
            byte[] buffer = new byte[1024];

            while (true) {
                DatagramPacket packet = new DatagramPacket(buffer, buffer.length);
                socket.receive(packet);
                speakers.write(packet.getData(), 0, packet.getLength());
            }
        } catch (IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }
}
